package bupt.party.online.action;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;

import bupt.party.online.model.Admin;
import bupt.party.online.model.LearnCenter;
import bupt.party.online.service.ILearnCenterService;
import bupt.party.online.util.SessionConstants;

/**
 * 学习公告的管理
 * @author ccna_zhang
 *
 */
@SuppressWarnings("serial")
public class NoticeAction extends Pagination implements SessionAware {

	private List<LearnCenter> learnCenters = new ArrayList<LearnCenter>();
	private Integer id; // 要查看或者修改的id
	private String content;  //学习园地的内容
	private String title = ""; // 查询时输入的学习园地的标题
	private ILearnCenterService learnCenterService; 
	private Map<String, Object> session;
	private String learnPosterName = "";   //发布者名字
	private String paginationCode = "";  //分页代码
	private LearnCenter learnCenter = new LearnCenter();  //封装保存或者要修改的学习园地
	private Integer flag = 5;
	private String result = ""; //标识检查权限后的转向逻辑
	private String queryTitle = ""; //保存查询时输入的标题
	
	public String getQueryTitle() {
		return queryTitle;
	}

	public void setQueryTitle(String queryTitle) {
		this.queryTitle = queryTitle;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	public List<LearnCenter> getLearnCenters() {
		return learnCenters;
	}

	public void setLearnCenters(List<LearnCenter> learnCenters) {
		this.learnCenters = learnCenters;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public ILearnCenterService getLearnCenterService() {
		return learnCenterService;
	}

	public void setLearnCenterService(ILearnCenterService learnCenterService) {
		this.learnCenterService = learnCenterService;
	}

	public String getLearnPosterName() {
		return learnPosterName;
	}

	public void setLearnPosterName(String learnPosterName) {
		this.learnPosterName = learnPosterName;
	}

	public String getPaginationCode() {
		return paginationCode;
	}

	public void setPaginationCode(String paginationCode) {
		this.paginationCode = paginationCode;
	}

	public LearnCenter getLearnCenter() {
		return learnCenter;
	}

	public void setLearnCenter(LearnCenter learnCenter) {
		this.learnCenter = learnCenter;
	}
	
	/**
	 * 获得请求的路径
	 * @return
	 */
	public String getServerPath() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String serverPath = request.getRequestURI().replace(".action", "");
		return serverPath.substring(1);
	}
	
	/**
	 * 查询学习公告，分页
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public String notice() {
	    		
		try {
			this.totalResults = learnCenterService.findLearnCenterCountByTitle(this.queryTitle, this.flag);  //查找总记录数
			
			if(this.totalResults % this.pageSize == 0) {  //设置总页数
				this.pageCount = this.totalResults/this.pageSize;
			} else {
				this.pageCount = this.totalResults/this.pageSize + 1;
			}
			
			this.learnCenters.clear();
			
			if(totalResults > 0) {
				
				String serverPath = this.getServerPath();
		        String url = serverPath + "?queryTitle=" + this.queryTitle.toString().trim();
				paginationCode = Pagination.getPaginationCodeByURL(pageSize, totalResults, pageNow, url); //获得分页的代码
				
				int currentIndex = (this.pageNow - 1) * this.pageSize;
				
				List list = this.learnCenterService.findAdminLearnCenterByTitle(this.queryTitle, flag, currentIndex, pageSize);
				
				if(list != null && list.size() > 0) {
					for(int i = 0; i < list.size(); i++) {  //遍历获得List中LearnCenter的信息
						Object[] obj = (Object[])list.get(i);
						LearnCenter learnCenter = new LearnCenter();
						learnCenter.setId((Integer)obj[0]);
						learnCenter.setTitle((String)obj[1]);
						learnCenter.setPosterNo((String)obj[2]);
						learnCenter.setPosterTime((Timestamp)obj[3]);
						learnCenter.setVisitsCount((Integer)obj[4]);
						learnCenter.setPosterName((String)obj[5]);
						this.learnCenters.add(learnCenter);
					}
				}
				
			} else {
				paginationCode = "没有查询到有效数据！";
			}
				
			return SUCCESS;	
			
		} catch(Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}
	
	/**
	 * 后台查询学习公告
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public String adminNotice() {
		if(!this.checkPermission()) {  //检查权限失败
			return this.result;
		} else {  //检查权限成功
			try {
				this.totalResults = learnCenterService.findLearnCenterCountByTitle(this.queryTitle, flag);  //查找总记录数
				
				if(this.totalResults % this.pageSize == 0) {  //设置总页数
					this.pageCount = this.totalResults/this.pageSize;
				} else {
					this.pageCount = this.totalResults/this.pageSize + 1;
				}
				
				this.learnCenters.clear();
				if(totalResults > 0) {
					
					String serverPath = this.getServerPath();
			        String url = serverPath + "?queryTitle=" + this.queryTitle.toString().trim();
			        
					paginationCode = Pagination.getPaginationCodeByURL(pageSize, totalResults, pageNow, url);
					
					int currentIndex = (this.pageNow - 1) * this.pageSize;
					List list = this.learnCenterService.findAdminLearnCenterByTitle(this.queryTitle, flag, currentIndex, pageSize);
							
					if(list != null && list.size() > 0) {
						for(int i = 0; i < list.size(); i++) {  //遍历获得List中LearnCenter的信息
							Object[] obj = (Object[])list.get(i);
							LearnCenter learnCenter = new LearnCenter();
							learnCenter.setId((Integer)obj[0]);
							learnCenter.setTitle((String)obj[1]);
							learnCenter.setPosterNo((String)obj[2]);
							learnCenter.setPosterTime((Timestamp)obj[3]);
							learnCenter.setVisitsCount((Integer)obj[4]);
							learnCenter.setPosterName((String)obj[5]);
							this.learnCenters.add(learnCenter);
						}
					}
				} else {
					paginationCode = "没有查询到有效数据！";
				}
					
				return SUCCESS;	
				
			} catch(Exception e) {
				e.printStackTrace();
				return ERROR;
			}
		}
	}
	
	/**
	 * 后台查询学习园地
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public String adminNoticeFenYe() {
		if(!this.checkPermission()) {  //检查权限失败
			return this.result;
		} else {  //检查权限成功
			try {
				this.totalResults = learnCenterService.findLearnCenterCountByTitle(this.queryTitle, flag);  //查找总记录数
				
				if(this.totalResults % this.pageSize == 0) {  //设置总页数
					this.pageCount = this.totalResults/this.pageSize;
				} else {
					this.pageCount = this.totalResults/this.pageSize + 1;
				}
				
				this.learnCenters.clear();
				
				if(totalResults > 0) {
					
					String serverPath = this.getServerPath();
			        String url = serverPath + "?queryTitle=" + this.queryTitle.toString().trim();

					paginationCode = Pagination.getPaginationCodeByURL(pageSize, totalResults, pageNow, url); //获得分页代码
					
					int currentIndex = (this.pageNow - 1) * this.pageSize;
					List list = this.learnCenterService.findAdminLearnCenterByTitle(this.queryTitle, flag, currentIndex, pageSize);
							
					if(list != null && list.size() > 0) {
						for(int i = 0; i < list.size(); i++) {  //遍历获得List中LearnCenter的信息
							Object[] obj = (Object[])list.get(i);
							LearnCenter learnCenter = new LearnCenter();
							learnCenter.setId((Integer)obj[0]);
							learnCenter.setTitle((String)obj[1]);
							learnCenter.setPosterNo((String)obj[2]);
							learnCenter.setPosterTime((Timestamp)obj[3]);
							learnCenter.setVisitsCount((Integer)obj[4]);
							learnCenter.setPosterName((String)obj[5]);
							this.learnCenters.add(learnCenter);
						}
					}
				} else {
					paginationCode = "没有查询到有效数据！";
				}
				
				return SUCCESS;	
				
			} catch(Exception e) {
				e.printStackTrace();
				return ERROR;
			}	
		}
	}
	
	/**
	 * 转到发布页面
	 * @return
	 */
	public String toPostNotice() {
		return "toPostNotice";
	}
	
	/**
	 * 管理员发布某个学习公告
	 * @return
	 */
	public String postNotice() {
		if(!this.checkPermission()) {
			return this.result;
		} else {
			try {
				Admin admin = (Admin)session.get(SessionConstants.SESSION_USER);
				if(admin == null) {  //如果Session过期，或者用户没有登录，则跳到登录界面
					return "loginUI";
				}
				
				//设置需要保存的学习园地的相关信息
				this.learnCenter.setIsDelete(0);
				this.learnCenter.setPosterNo(admin.getAdminNo());
				this.learnCenter.setPosterTime(new Timestamp(System.currentTimeMillis()));
				this.learnCenter.setTag(this.flag);
				this.learnCenter.setVisitsCount(0);
				this.learnCenter.setContent(this.content);
				this.learnCenter.setTitle(this.title);
				this.learnCenterService.saveLearnCenter(this.learnCenter);
				
				return "toNoticeList";
				
			} catch(Exception e) {
				e.printStackTrace();
				return ERROR;
			}
		}
	}
	
	/**
	 * 跳到更新学习公告的页面
	 * @return
	 */
	public String toUpdateNotice() {
		if(!this.checkPermission()) {
			return this.result;
		} else {
			this.learnCenter = this.learnCenterService.findLearnCenterById(id);
			return "toUpdateNotice";
		}
	}
	
	/**
	 * 更新某个学习公告
	 * @return
	 */
	public String updateNotice() {
		if(!this.checkPermission()) {
			return this.result;
		} else {
			Admin admin = (Admin)session.get(SessionConstants.SESSION_USER);
			if(admin == null) {
				return LOGIN;
			}
			try {
				this.learnCenter = this.learnCenterService.findLearnCenterById(id);
				this.learnCenter.setModifyNo(admin.getAdminNo());
				this.learnCenter.setModifyTime(new Timestamp(System.currentTimeMillis()));
				this.learnCenter.setTitle(this.title);
				this.learnCenter.setContent(this.content);
				this.learnCenter.setTag(this.flag);
				this.learnCenter.setIsDelete(0);
				this.learnCenterService.updateLearnCenter(learnCenter);
				return "toNoticeList";
				
			} catch(Exception e) {
				e.printStackTrace();
				return ERROR;
			}
		}
	}
	
	/**
	 * 删除某个学习公告
	 * @return
	 */
	public String deleteNotice() {
		if(!this.checkPermission()) {
			return this.result;
		} else {
			try {
				this.learnCenterService.deleteLearnCenterById(id);
				return "toNoticeList";
			} catch(Exception e) {
				e.printStackTrace();
				return ERROR;
			}
		}
	}
	
	/**
	 * 根据id查看学习公告
	 * @return
	 */
	public String viewNotice() {
		try {
			this.learnCenterService.addLearnCenterVisitsCount(id);
			this.learnCenter = this.learnCenterService.findLearnCenterById(id);  //根据id查找到某个学习园地
			return "viewNotice";
		} catch(Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}
	
	/**
	 * 后台管理员的根据id查看学习公告的内容
	 * @return
	 */
	public String viewAdminNotice() {
		if(!this.checkPermission()) {
			return this.result;
		} else {
			try {
				this.learnCenter = this.learnCenterService.findLearnCenterById(id);
				return "viewAdminNotice";
			} catch(Exception e) {
				e.printStackTrace();
				return ERROR;
			}
		}
	}

	/**
	 * 
	 * @return
	 */
	private boolean checkPermission() {
	  Integer level = (Integer)session.get(SessionConstants.LEVEL); //首先获得level 
	  boolean flag = false;
	  if(level == null) {  //用户没有登录
		  result = "loginUI";
	  } else if(level != SessionConstants.ADMIN_THIRD_LEVEL) { //不是学校管理员
		  result = "noPermission";
	  } else {    //是学校管理员
		  flag = true;
	  }
	  return flag;
	}
}
